23. Exercise: Navigate on Click
L7 39 Navigate On Click SC
Now it’s your turn to complete this exercise yourself!
In this exercise you'll change your listener to navigate to a new fragment and pass the data.
**Open fragment_sleep_detail.xml and uncomment the code inside the ConstraintLayout.
In SleepTrackerFragment, update the SleepNightListener code to pass the data to view model.
val adapter = SleepNightAdapter(SleepNightListener { nightId -> sleepTrackerViewModel.onSleepNightClicked(nightId) })In SleepTrackerViewModel, add a handler for the click event.
You also need to add a
MutableLiveDataobject to control the navigation.private val _navigateToSleepDataQuality = MutableLiveData<Long>() val navigateToSleepDataQuality get() = _navigateToSleepDataQualityDefine method to initiate and complete naviattion.
Initiate navigation by setting _navigateToSleepDataQuality.value to
id:fun onSleepNightClicked(id: Long){ _navigateToSleepDataQuality.value = id }and then set it to
nullonce navigation is completed:fun onSleepDataQualityNavigated() { _navigateToSleepDataQuality.value = null }In
SleepTrackerFragment, add an observer to trigger navigation when the listener passes the data toViewModel.Make sure you call
onSleepDataQualityNavigatedwhen navigation is complete.sleepTrackerViewModel.navigateToSleepDataQuality.observe(this, Observer {night -> night?.let { this.findNavController().navigate(SleepTrackerFragmentDirections .actionSleepTrackerFragmentToSleepDetailFragment(night)) sleepTrackerViewModel.onSleepDataQualityNavigated() } })
If you want to start at this step, you can download this exercise from: Step.12-Exercise-Navigate-on-Click.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here: Step.12-Solution-Navigate-on-Click, or using this git diff.
Task Description:
Complete these tasks to navigate to a new fragment and pass data.
Task Feedback:
Congratulations, you now have a working RecyclerView with navigation!